#!/usr/bin/python3
# -*- coding: utf-8 -*-

import json
import re
from typing import List

import allure
from playwright.sync_api import Page

from utils.allure_util import ath
from utils.log import log


class Table:
    def __init__(self, page: Page, timeout=5000):
        self.page = page
        self.table_main = self.page.locator(".table")
        self.table_header = self.table_main.locator("thead")
        self.table_rows = self.table_main.locator("tbody tr")
        self.table_columns = self.table_main.locator("thead tr th")
        self.checkbox = self.page.get_by_role("checkbox")
        self.timeout = timeout

    @allure.step("表格：[获取表格总行数]")
    def get_table_tr_num(self):
        """获取表格行数"""
        num = self.table_rows.count()
        log.info(f"表格行数:{num}")
        if num is not None:
            return int(num)
        else:
            return 0

    @allure.step("表格：[获取某行数据]")
    def get_table_tr_text(self, row_index: int = 0):
        """获取表格指定行的文本,默认第一行"""
        row = self.table_rows.nth(index=row_index)
        text = row.inner_text().replace("\n", "").strip()
        log.info(f"获取表格第{row_index}行的文本:{text}")
        ath.text(text, f"第{row_index}行数据")
        return text

    @allure.step("表格：[获取所有数据]")
    def get_table_all_text(self) -> List[List[str]]:
        """获取表格所有数据 .strip().split("\t")"""
        texts = []
        text_lines = self.table_rows.all()
        for text_line in text_lines:
            text = re.split(
                r"\s+", text_line.inner_text().replace("\n", "").strip().strip()
            )
            texts.append(text)
        log.info(f"表格所有数据:{texts}")
        ath.text(json.dumps(texts), "table text")
        return texts

    @allure.step("表格：[勾选复选框-全选]")
    def select_all_checkbox(self):
        """全选列表页所有项"""
        log.info("全选列表页所有项")
        self.checkbox.first.check()

    def get_cell_by_keyword(self, keyword: str):
        """根据cell内的关键字获取cell"""
        return self.page.get_by_role("cell", name=keyword)

    def get_cell_by_index(self, row_index: int, col_index: int):
        """根据行和列的索引获取cell"""
        row = self.table_rows.nth(index=row_index)
        return row.locator("td").nth(col_index)

    def check_checkbox(self, row_keyword: str = None, row_index: int = 0):
        """勾选指定行的checkbox，默认勾选第一行
        params：
            row_keyword: 根据内行的关键字获取该行的checkbox
            row_index: 根据行的索引获取该行的checkbox，默认取第一行
        """
        row_checkbox = self.table_rows.nth(row_index).get_by_role("checkbox")
        if row_keyword:
            row_checkbox = self.table_rows.get_by_role(
                "row", name=re.compile(f"{row_keyword}")
            ).get_by_role("checkbox")
        row_checkbox.check()

    @allure.step("根据关键字勾选复选框")
    def click_checkbox_by_keyword(self, row_keyword=""):
        """根据关键字，点击列表页所有项的checkbox"""
        log.info("根据关键字勾选复选框")
        if not row_keyword:
            return
        table_nums = self.get_table_tr_num()
        if table_nums > 0:
            for row in range(1, table_nums + 1):
                text = self.page.evaluate(
                    f'document.querySelectorAll("table tr")[{row}].textContent'
                )
                log.debug(
                    f"关键字:{row_keyword} - 目标文本:{text} - 关键字是否在目标文本中:{row_keyword in text}"
                )
                if row_keyword in text:
                    try:
                        checkbox_locator = self.page.wait_for_selector(
                            f'tbody tr:nth-child({row}) input[type="checkbox"]',
                            state="attached",
                        )
                        if checkbox_locator:
                            checkbox_locator.check()
                            log.debug(
                                f"{checkbox_locator}: 是否可见: {checkbox_locator.is_checked()}"
                            )
                            break
                    except Exception as e:
                        log.debug(f"Error checking checkbox: {e}")
